//
//  TNCityViewController.m
//  TravelNotes
//
//  Created by 黄锋 on 15/8/11.
//  Copyright (c) 2015年 王浩宇. All rights reserved.
//

#import "TNCityViewController.h"
#import "Macro.h"
#import "TNCountryModel.h"
#import <AFNetworking.h>
#import "TNCityTableHeaderView.h"
#import "TNCityTableViewCell.h"
#import "MBProgressHUD.h"

#define kURL0 @"http://chanyouji.com/api/wiki/destinations.json?page=1"
#define kDestinationsInfos @"destinationsInfos"

@interface TNCityViewController () <UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate>

@property(nonatomic, strong) UISegmentedControl *segmentedControl;
@property(nonatomic, strong) UIScrollView *scrollView;
@property(nonatomic, strong) UITableView *tableView;//国外
@property(nonatomic, strong) UITableView *tableView1;//国内
@property(nonatomic, strong) NSMutableArray *overseasArr; //国外
@property(nonatomic, strong) NSMutableArray *internalArr;  //国内
@property(nonatomic) NSInteger seletedSection;
@property(nonatomic) NSInteger seletedSection1;
@property(nonatomic, strong) MBProgressHUD *hud;  //大菊花
@property(nonatomic, strong) UIAlertView *alertView;

@end

@implementation TNCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"选择目的地";
    self.view.backgroundColor = [UIColor whiteColor];
    _overseasArr = [NSMutableArray array];
    _internalArr = [NSMutableArray array];
    _seletedSection = INT32_MAX;
    _seletedSection1 = INT32_MAX;
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 20, 40, 40);
    [leftButton setImage:[UIImage imageNamed:@"BackBarButton"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(popAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    [self creatView];
    [self creatHud];
}

- (void)popAction
{
    NSNumber *number = [[NSUserDefaults standardUserDefaults] objectForKey:kDestinationsInfos];
    if (number) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        _alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请选择目的地" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        _alertView.delegate = self;
        [_alertView show];
        [self performSelector:@selector(alertViewRemove) withObject:self afterDelay:.5];
    }
}

- (void)alertViewRemove
{
    [_alertView dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)creatHud
{
    _hud = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
    [self.view addSubview:_hud];
    [_hud show:YES];
    [self parserData];
}

- (void)hudHidden
{
    [_hud removeFromSuperview];
    [_hud show:NO];
    if (_seletedSection < INT32_MAX) {
        [_tableView reloadData];
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_seletedSection] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    } else if(_seletedSection1 < INT32_MAX) {
        _segmentedControl.selectedSegmentIndex = 1;
        _scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
        [_tableView1 reloadData];
        [_tableView1 scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_seletedSection1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    } else {
        [_tableView reloadData];
    }
}

- (void)creatView
{
    _segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"国外", @"国内"]];
    _segmentedControl.frame = CGRectMake(10, 70, SCREEN_WIDTH - 20, 30);
    [_segmentedControl addTarget:self action:@selector(segmentedControlValueChanged:) forControlEvents:UIControlEventValueChanged];
    _segmentedControl.selectedSegmentIndex = 0;
    [self segmentedControlValueChanged:_segmentedControl];
    [self.view addSubview:_segmentedControl];
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 105, SCREEN_WIDTH, SCREEN_HEIGHT - 105)];
    _scrollView.tag = 10000;
    _scrollView.contentSize = CGSizeMake(2 * SCREEN_WIDTH, SCREEN_HEIGHT - 105);
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    _scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 105 ) style:UITableViewStyleGrouped];
    _tableView .tag = 100;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 40;
    _tableView.tableHeaderView.frame = CGRectZero;
    [_tableView registerClass:[TNCityTableViewCell class] forCellReuseIdentifier:@"TNCityTableViewCell"];
    [_tableView registerClass:[TNCityTableHeaderView class] forHeaderFooterViewReuseIdentifier:@"TNCityTableHeaderView"];
    [_scrollView addSubview:_tableView];
    
    _tableView1 = [[UITableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 105) style:UITableViewStyleGrouped];
    _tableView1.tag = 101;
    _tableView1.delegate = self;
    _tableView1.dataSource = self;
    _tableView1.rowHeight = 40;
    _tableView1.tableHeaderView.frame = CGRectZero;
    [_tableView1 registerClass:[TNCityTableViewCell class] forCellReuseIdentifier:@"TNCityTableViewCell"];
    [_tableView1 registerClass:[TNCityTableHeaderView class] forHeaderFooterViewReuseIdentifier:@"TNCityTableHeaderView"];
    [_scrollView addSubview:_tableView1];
}

//获取国内/国外国家(城市)信息
- (void)parserData
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:kURL0 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSNumber *number = [[NSUserDefaults standardUserDefaults] objectForKey:kDestinationsInfos];
        BOOL choose = NO;
        NSInteger count = 0;
        NSInteger count1 = 0;
        for (int k = 0; k < array.count; k++) {
            NSDictionary *dic = array[k];
            NSArray *array1 = dic[@"destinations"];
            for (int i = 0; i < array1.count; i++) {
                NSDictionary *dic1 = array1[i];
                TNCountryModel *model = [[TNCountryModel alloc] init];
                [model setValuesForKeysWithDictionary:dic1];
                NSNumber *num = dic[@"category"];
                if (number) {
                    if (!choose) {
                        count++;
                        if ([num integerValue] >= 99) {
                            count1++;
                        }
                        NSArray *array2 = model.children;
                        for (int j = 0; j < array2.count; j++) {
                            NSDictionary *dic2 = array2[j];
                            if ([dic2[@"id"] isEqualToNumber:number]) {
                                if ([num integerValue] < 99) {
                                    _seletedSection = count - 1;
                                } else {
                                    _seletedSection1 = count1 - 1;
                                }
                                choose = YES;
                            }
                        }
                    }
                }
                if ([num integerValue] < 99) {
                    [_overseasArr addObject:model];
                } else {
                    [_internalArr addObject:model];
                }
            }
        }
        [self hudHidden];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_hud removeFromSuperview];
        [_hud show:NO];
        UIAlertView *view = [[UIAlertView alloc] initWithTitle:nil message:@"网络出错" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"重试", nil];
        [view show];
    }];
}

- (void)dismissAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)segmentedControlValueChanged:(UISegmentedControl *)sender
{
    NSInteger index = _segmentedControl.selectedSegmentIndex;
    _scrollView.contentOffset = CGPointMake(index * SCREEN_WIDTH, 0);
    if (index == 0) {
         [_tableView reloadData];
    } else {
         [_tableView1 reloadData];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.tag == 10000) {
        NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
        if (_segmentedControl.selectedSegmentIndex != index) {
            _segmentedControl.selectedSegmentIndex = index;
            [self segmentedControlValueChanged:_segmentedControl];
        }
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self creatHud];
    }
}

#pragma mark - tableView

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 60;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView.tag == 100) {
        return _overseasArr.count;
    } else {
         return _internalArr.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 100) {
        if (section == _seletedSection) {
            TNCountryModel *model = _overseasArr[section];
            return model.children.count;
        }
    } else {
        if (section == _seletedSection1) {
            TNCountryModel *model = _internalArr[section];
            return model.children.count;
        }
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    TNCityTableHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"TNCityTableHeaderView"];
    if (!view) {
        view = [[TNCityTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
    }
    view.myblock = ^() {
        if (tableView.tag == 100) {
            if (section == _seletedSection) {
                _seletedSection = INT32_MAX;
            } else {
                _seletedSection = section;
            }
        } else {
            if (section == _seletedSection1) {
                _seletedSection1 = INT32_MAX;
            } else {
                _seletedSection1 = section;
            }
        }
        [tableView reloadData];
    };
    TNCountryModel *model = nil;
     if (tableView.tag == 100) {
         model = _overseasArr[section];
         if (section == _seletedSection) {
             view.pic.image = [UIImage imageNamed:@"jiantou"];
         }
     } else {
         model = _internalArr[section];
         if (section == _seletedSection1) {
             view.pic.image = [UIImage imageNamed:@"jiantou"];
         }
     }
    view.countryLable.text = model.name_zh_cn;
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TNCityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TNCityTableViewCell" forIndexPath:indexPath];
    TNCountryModel *model = nil;
    if (tableView.tag == 100) {
        model = _overseasArr[indexPath.section];
    } else {
        model = _internalArr[indexPath.section];
    }
    NSDictionary *dic = model.children[indexPath.row];
    cell.name.text = dic[@"name_zh_cn"];
    NSNumber *number = [[NSUserDefaults standardUserDefaults] objectForKey:kDestinationsInfos];
    if ([number isEqualToNumber:dic[@"id"]]) {
        cell.image.image = [UIImage imageNamed:@"gou"];
    } else {
        cell.image.image = nil;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TNCountryModel *model = nil;
    if (tableView.tag == 100) {
        model = _overseasArr[indexPath.section];
    } else {
        model = _internalArr[indexPath.section];
    }
    NSDictionary *dic = model.children[indexPath.row];
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:dic[@"id"] forKey:kDestinationsInfos];
    [ud setObject:dic[@"name_zh_cn"] forKey:@"cityName"];
    [ud synchronize];
    if (_delegate && [_delegate respondsToSelector:@selector(seleteCity)]) {
        [_delegate seleteCity];
    }
    [self dismissAction];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
